/**
 * 登录组件
 * */

import React, {Component} from "react";
import {connect} from 'react-redux'
import {login} from 'src/api/request';
import {withRouter} from 'react-router-dom'
import LoginRegisterBottom from '../../components/Bottom/LoginRegisterBottom/LoginRegisterBottom'

import {Form} from 'antd'
import LoginForm from "../../components/LoginForm/LoginForm";


class Login extends Component {
  /**
   * 构造函数、初始化state
   * */
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      password: '',
      errorInfo: '',
      isLoading: false
    }
  }

  /**
   * 表单提交成功
   * */
  onFinish = values => {
    this.setState({
      isLoading: true,
      username: values.username,
      password: values.password,
    });
    this.props.login(this.state).then(
      () => {
        this.props.history.push('/')
      },
      () => {
        this.setState({
          isLoading: false,
          errorInfo: ''
        });
        this.props.history.push('/login')
      },
    )
  };

  /**
   * 表单提交失败（表单验证失败）
   * */
  onFinishFailed = errorInfo => {
    console.log("验证失败", errorInfo)
  };


  // 跳转到注册路由
  toRegister = () => {
    this.props.history.replace('/register')
  };

  render() {
    const {isLoading} = this.state;
    return (
      <div className='login'>
        <Form
          layout='horizontal'
          onFinish={this.onFinish}
          onFinishFailed={this.onFinishFailed}
          scrollToFirstError>
          <LoginForm status={isLoading}/>
        </Form>
        <div className={'link'}>
          <span>新用户？</span>
          <span onClick={this.toRegister}>注册</span>
        </div>
        <LoginRegisterBottom/>
      </div>
    )
  }
}


export default withRouter(connect(
  null,
  {login}
)(Login))